<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;

use DB;

class adminUserNameController extends Controller
{
    //admin首页
    public function index()
    {
    	if ((session("adminUser")['attributes']['adminAuth'] != 1)) {
            $list = DB::table('storeAdmin')->where('adminId',session('adminUser')->adminId)->get();
    		
    		return view('admin.table',['list' => $list]);
    	};
    	$list = DB::table('storeAdmin')->paginate(1);;

    	return view('admin.table',['list' => $list]);
    }

    // admin添加页面
    public function create()
    {
    	return view('admin.addAdmin');
    }

    public function store(Request $request)
    {

    	//判断密码是否相等
    	if ($request->input('adminPass') != $request->input('pass') ) {

    		return back()->with('msg','两次密码不相同');
    	}

    	//自定义错误信息
    	$message = [
    		'required' => ':attribute 的字段是必须的',

    	];

    	//设定验证规则
    	$this -> validate($request,[
    		'adminName' => 'required|unique:storeAdmin',
    		'adminPass' => 'required|unique:storeAdmin',
    		'pass' => 'required',
    	],$message);

    
    	$data = $request->except('_token','pass');
    	// $data['adminPass'] = md5($request->('adminPass'));
    	$data = array('adminName'=>$data['adminName'],'adminPass' => md5($data['adminPass']));
    	// dd($data);
    	$id = DB::table('storeAdmin')->insertGetId($data);
    	if ($id>0) {
    		
    		return redirect('admin/adminUserName')->with('msg','添加成功');
    	}


    }

    // admin修改页面
    public function edit($id)
    {	

    	$list = DB::table('storeAdmin')->where('adminId',$id)->first();
    	return view('admin.editAdmin',['list' => $list]);
    }

    //admin修改结果
    public function update($id,Request $request)
    {
    	

    	//判断两次密码是否相等
    	if ( $request->input('adminPass') != $request->input('pass')) {

    		return back()->with('msg','两次密码不相同');
    	}
    	//自定义错误信息
    	$message = [
    		'required' => ':attribute 的字段是必须的',
    		'unique' => '字段唯一的',
    	];

    	//设定验证规则
    	$this -> validate($request,[
    		'adminName' => 'required|unique:storeAdmin',
    		'adminPass' => 'required',
    		'pass' => 'required',
    		],$message);

    	//执行修改
    	$data = $request -> except('_token','_method','pass');
    	$data['adminPass'] = md5($data['adminPass']);
    	$row = DB::table('storeAdmin') -> where('adminId',$id) -> update($data);
    	if ( $row > 0 ) {

    		return redirect('admin/adminUserName')->with('msg','修改成功');
    	}
    	
    }

    //删除管理员
    public function destroy($id)
    {
    	$row = DB::table('storeAdmin')->where('adminId',$id)->delete();

    	if ( $row >0 ) {
    		return back()->with('msg','删除成功');
    	}
    }
}
